import datetime

from sqlalchemy import extract
from sqlalchemy.sql.functions import sum

from app.models import db
from app.models.collection import DataCollection
from app.models.parking_rate import ParkingRate
from app.models.road_toll import RoadToll
from app.models.ruel_cost import RuelCost


def get_car_mileage_date(car, year=None, month=None):
    # 查询车的年每月里程总和
    if year is None:
        year = datetime.datetime.now().year
    if month is None:
        date = "month"
    else:
        date = "day"

    car_data = (
        db.session.query(
            extract(date, DataCollection.create_time).label("date"),
            sum(DataCollection.course).label("total"),
        )
        .filter(
            extract("year", DataCollection.create_time) == year,
            car.id == DataCollection.car,
        )
        .group_by("date")
        .all()
    )

    return car_data


def get_car_cost_date(car, year=None, month=None):
    if year is None:
        year = datetime.datetime.now().year
    if month is None:
        date = "month"
    else:
        date = "day"

    car_ruel = (
        db.session.query(
            extract(date, RuelCost.create_time).label("date"),
            sum(RuelCost.total_price).label("total"),
        )
        .filter(
            extract("year", RuelCost.create_time) == year,
            car.id == RuelCost.car,
        )
        .group_by("date")
        .all()
    )

    car_parking = (
        db.session.query(
            extract(date, ParkingRate.create_time).label("date"),
            sum(ParkingRate.price).label("total"),
        )
        .filter(
            extract("year", ParkingRate.create_time) == year,
            car.id == ParkingRate.car,
        )
        .group_by("date")
        .all()
    )
    car_road = (
        db.session.query(
            extract(date, RoadToll.create_time).label("date"),
            sum(RoadToll.price).label("total"),
        )
        .filter(
            extract("year", RoadToll.create_time) == year,
            car.id == RoadToll.car,
        )
        .group_by("date")
        .all()
    )

    return car_ruel, car_road, car_parking


def car_mileage_time_list(car_data, response_body):
    # 生成里程时间数据
    cd_dict = {}
    for cd in car_data:
        if cd.date not in response_body["data_xAxis"]:
            response_body["data_xAxis"].append(cd.date)
        cd_dict[cd.date] = cd.total

    response_body["data_xAxis"].sort(reverse=False)
    return cd_dict


def make_mileage_response(li_data_dict, response_body):
    for car_num, value in li_data_dict.items():
        car_data_list = []
        for tm in response_body["data_xAxis"]:
            if value.get(tm):
                car_data_list.append(value.get(tm))
            else:
                car_data_list.append(0)

        response_body["data"].append(
            {"name": car_num, "type": "bar", "barWidth": "10%", "data": car_data_list},
        )


def car_cost_list(car_ruel, car_road, car_parking, response_body):
    # 价格数据
    cost_data_dict = {}
    for ruel in car_ruel:
        if ruel.date not in response_body.get("cost_xAxis"):
            response_body["cost_xAxis"].append(ruel.date)
            cost_data_dict[ruel.date] = ruel.total
        elif not cost_data_dict.get(ruel.date):
            cost_data_dict[ruel.date] = ruel.total

    for road in car_road:
        if road.date not in response_body.get("cost_xAxis"):
            response_body["cost_xAxis"].append(road.date)
            cost_data_dict[road.date] = road.total
        elif not cost_data_dict.get(road.date):
            cost_data_dict[road.date] = road.total

        else:
            cost_data_dict[road.date] = cost_data_dict[road.date] + road.total

    for park in car_parking:
        if park.date not in response_body.get("cost_xAxis"):
            response_body["cost_xAxis"].append(park.date)
            cost_data_dict[park.date] = park.total
        elif not cost_data_dict.get(park.date):
            cost_data_dict[park.date] = park.total
        else:
            cost_data_dict[park.date] = cost_data_dict[park.date] + park.total

    return cost_data_dict


def make_cost_response(response_body, cost_data_dict):

    # 生成价格list
    response_body["cost_xAxis"].sort(reverse=False)

    for car_name, value in cost_data_dict.items():
        # 生成价格列表
        cost_list = []
        for tm in response_body["cost_xAxis"]:
            if value.get(tm):
                cost_list.append(value.get(tm))
            else:
                cost_list.append(0)
        response_body["cost"].append(
            {"name": car_name, "type": "bar", "barWidth": "20%", "data": cost_list},
        )
